package com.lely.controller;

import com.lely.entity.Role;
import com.lely.result.Response;
import com.lely.service.RoleService;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lely
 * @date 2021/4/15 11:24
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * note: 查询单个角色信息
     * @param id
     * @return
     */
    @GetMapping("/role/{id}")
    public Response getRole(@PathVariable("id") Long id) {
        Role role = roleService.get(id);
        if(role==null){
            return new Response("200","暂无数据",null);
        }
        return new Response(role);
    }

    /**
     * note：分页列表查询用户
     * @param map: 分页相关信息
     * @return
     */
    @PostMapping("/getAll")
    public Response getRoleAll(Map map) {
        List<Role> all = roleService.getAll(map);
        if(all==null||all.size()==0){
            return new Response("200","暂无数据",null);
        }
        return new Response(all);
    }

    /**
     * @param role:新建的角色信息,需要判断角色名是否存在
     * @return
     */
    @PostMapping("/role")
    public Response createRole(@RequestBody Role role) {
        Integer count1 = roleService.count(role.getRoleName());
        if(count1 > 0){
            return new Response("-100","添加角色失败，角色名称已存在",null);
        }
        Integer count = roleService.add(role);
        if(count==1){
            return new Response( null);
        }else{
            return new Response("-100","添加失败，other",null);
        }
    }

    /**
     * @param role：需要修改的信息
     * @return
     */
    @PutMapping("/role")
    public Response updateRole(@RequestBody Role role) {
        int count = roleService.update(role);
        if(count>0){
            return new Response("200","更新成功",null);
        }
        return new Response("-100","更新失败",null);
    }

    /**
     * @param id: 需要删除的用户 id
     * @return
     */
    @DeleteMapping("/role/{id}")
    public Response delete(@PathVariable("id") Long id) {
        int count = roleService.delete(id);
        if(count>0){
            return new Response("200","角色删除成功",null);
        }
        return new Response("-100","角色删除失败，改角色权限已经分配给其它用户",null);
    }
}
